<template>
  <div class="login-view-container">
    <div class="background-shapes">
      <div class="shape circle-1"></div>
      <div class="shape circle-2"></div>
    </div>
    
    <div class="login-form-container">
      <div class="form-header">
        <h2>欢迎回来</h2>
        <p>请登录您的账户</p>
      </div>
      
      <form @submit.prevent="handleLogin">
        <div class="input-group">
          <i class="fas fa-user"></i>
          <input 
            type="text" 
            v-model="loginData.account" 
            placeholder="账号名" 
            required
            :disabled="loading"
          >
        </div>
        
        <div class="input-group">
          <i class="fas fa-lock"></i>
          <input 
            :type="showPassword ? 'text' : 'password'" 
            v-model="loginData.password" 
            placeholder="密码" 
            required
            :disabled="loading"
          >
          <i 
            :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'" 
            @click="togglePasswordVisibility"
            class="password-toggle"
          ></i>
        </div>
        
        <div class="remember-forgot">
          <label>
            <input type="checkbox" v-model="rememberMe" :disabled="loading"> 记住我
          </label>
          <a href="#" @click.prevent="handleForgotPassword">忘记密码?</a>
        </div>
        
        <button type="submit" class="login-btn" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '登录中...' : '登录' }}
        </button>
        
        <div class="divider">
          <span>或</span>
        </div>
        
        <div class="social-login">
          <button type="button" class="social-btn google-btn" :disabled="loading">
            <i class="fab fa-google"></i> Google
          </button>
          <button type="button" class="social-btn github-btn" :disabled="loading">
            <i class="fab fa-github"></i> GitHub
          </button>
        </div>
        
        <p class="register-link">
          还没有账户? <a href="#" @click.prevent="navigateToRegister">立即注册</a>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  login,
  selectEq,
  type LoginRequest,
  type User
} from '@/http/User';
import { useUserIdStore } from '@/stores/UserId';
import { message } from '@/utils/message';

const userIdStore = useUserIdStore();
const router = useRouter();

// 响应式数据
const loginData = ref<LoginRequest>({
  account: '',
  password: ''
});

const loading = ref(false);
const rememberMe = ref(false);
const showPassword = ref(false);

// 页面加载时恢复状态
onMounted(() => {
  userIdStore.restoreFromStorage();
  
  // 如果已经登录，直接跳转到用户页面
  if (userIdStore.isAuthenticated) {
    message.info('您已经登录，正在跳转...');
    router.push('/user');
  }
  
  // 如果选择了记住我，恢复账号
  const savedAccount = localStorage.getItem('savedAccount');
  if (savedAccount) {
    loginData.value.account = savedAccount;
    rememberMe.value = true;
  }
});

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 处理忘记密码
const handleForgotPassword = () => {
  message.info('忘记密码功能开发中，请联系管理员');
};

// 登录处理函数
const handleLogin = async () => {
  if (!loginData.value.account.trim()) {
    message.warning('请输入账号');
    return;
  }
  
  if (!loginData.value.password.trim()) {
    message.warning('请输入密码');
    return;
  }
  
  loading.value = true;
  
  try {
    // 方案1：如果后端有专门的登录接口，使用login方法
    // const response = await login(loginData.value);
    // const user = response.data.user;
    // const token = response.data.token;
    
    // 方案2：使用现有的selectEq接口进行登录验证
    const query: Record<string, any> = {
      account: loginData.value.account,
      password: loginData.value.password
    };
    
    const response = await selectEq(query);
    
    if (response.data && response.data.length > 0) {
      const user = response.data[0];
      
      // 保存用户信息到状态管理
      userIdStore.login(user, undefined, 'Login');
      
      // 记住账号
      if (rememberMe.value) {
        localStorage.setItem('savedAccount', loginData.value.account);
      } else {
        localStorage.removeItem('savedAccount');
      }
      
      message.success('登录成功！');
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/user');
      }, 1000);
      
    } else {
      message.error('账号或密码错误');
    }
    
  } catch (error: any) {
    console.error('登录失败:', error);
    
    if (error.message) {
      message.error(error.message);
    } else {
      message.error('登录失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
};

// 导航到注册页面
const navigateToRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-view-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.background-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
}

.circle-1 {
  width: 400px;
  height: 400px;
  background: linear-gradient(45deg, #ff9a9e, #fad0c4);
  top: -200px;
  left: -150px;
}

.circle-2 {
  width: 300px;
  height: 300px;
  background: linear-gradient(45deg, #a1c4fd, #c2e9fb);
  bottom: -150px;
  right: -100px;
}

.login-form-container {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
  z-index: 1;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.form-header p {
  color: #7f8c8d;
  font-size: 1.1rem;
}

.input-group {
  position: relative;
  margin-bottom: 25px;
}

.input-group i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7f8c8d;
  font-size: 18px;
}

.input-group input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 1px solid #e1e5eb;
  border-radius: 10px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.input-group input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

.input-group .fa-eye {
  left: auto;
  right: 15px;
  cursor: pointer;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  font-size: 0.9rem;
}

.remember-forgot label {
  display: flex;
  align-items: center;
  color: #7f8c8d;
  cursor: pointer;
}

.remember-forgot input {
  margin-right: 8px;
}

.remember-forgot a {
  color: #3498db;
  text-decoration: none;
}

.remember-forgot a:hover {
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(to right, #3498db, #1abc9c);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 加载动画 */
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 密码切换按钮 */
.password-toggle {
  left: auto !important;
  right: 15px !important;
  cursor: pointer;
  transition: color 0.3s ease;
}

.password-toggle:hover {
  color: #3498db;
}

/* 禁用状态的输入框 */
.input-group input:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
  opacity: 0.7;
}

/* 禁用状态的复选框 */
.remember-forgot input:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.divider {
  display: flex;
  align-items: center;
  margin: 25px 0;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #e1e5eb;
}

.divider span {
  padding: 0 15px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.social-login {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
}

.social-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.google-btn {
  background: white;
  color: #db4437;
  border: 1px solid #e1e5eb;
}

.github-btn {
  background: #333;
  color: white;
}

.social-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.register-link {
  text-align: center;
  color: #7f8c8d;
}

.register-link a {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-form-container {
    padding: 30px 20px;
  }
  
  .social-login {
    flex-direction: column;
  }
}
</style>